import React, { useRef, useState } from 'react'
import { Button, message, Popconfirm, Switch } from 'antd'
import { PageContainer } from '@ant-design/pro-layout'
import ProTable from '@ant-design/pro-table'
import { PlusOutlined } from '@ant-design/icons'
import { categoryChangeStatus, categoryList, createCategory, putCategory } from '@/services/category'
import CreateForm from '@/pages/Category/components/CreateForm'
import UpdateForm from '@/pages/Category/components/UpdateForm'
import GetTime from '@/components/GetTime'

const Index = (props) => {
  /** 设置loading **/
  const [loading, setLoading] = useState(false)
  /** 设置创建表单是否显示 **/
  const [createModalVisit, setCreateModalVisit] = useState(false)
  /** 设置修改表单是否显示 **/
  const [updateModalVisit, setUpdateModalVisit] = useState(false)
  /** 设置修改需要字段 **/
  const [categoryDetail, setCategoryDetail] = useState(undefined)
  /** 设置修改需要字段 **/
  const [categoryLists, setCategoryLists] = useState([])
  /** 设置分组 **/
  const group = {
    'subject': '科目分类',
    'examination': '考试分类',
    'paper': '试卷分类',
    'text-bank': '题库分类',
    'menu': '菜单分类',
  }
  /** 设置树状图 **/
  const treeData = data => {
    let newData = data.map(item => {
      return {
        key: item.id,
        value: item.id,
        title: item.name,
        children: item.children ? item.children.map(item => {
          return {
            key: item.id,
            value: item.id,
            title: item.name,
          }
        }) : []
      }
    })
    newData.unshift({ key: 0, value: 0, title: '顶级分类', children: [] })
    return newData
  }

  const actionRef = useRef()

  /**
   * 处理分类禁用启用
   * @param value
   */
  const handleChangeStatus = async value => {
    setLoading(true)
    const response = await categoryChangeStatus(value.id)
    if (response === '') {
      message.success('操作成功')
      setLoading(false)
    }
  }

  /**
   * 处理创建分类
   * @param values
   */
  const handleCreateCategory = async values => {
    setLoading(true)
    if (values.pid === 0) {
      delete values.pid
    }

    const response = await createCategory(values)
    if (response === '') {
      actionRef.current.reload()
      message.success('添加成功')
      setLoading(false)
      // 关闭模态框
      setCreateModalVisit(false)
    } else {
      setLoading(false)
    }
  }

  /**
   * 处理修改分类
   * @param values
   */
  const updateCategory = async values => {
    setLoading(true)
    const response = await putCategory(values.id, values)
    if (response === '') {
      actionRef.current.reload()
      message.success('修改成功')
      setLoading(false)
      // 关闭模态框
      setUpdateModalVisit(false)
    } else {
      setLoading(false)
    }
  }

  /** 定义字段 **/
  const columns = [
    {
      title: '编号',
      key: 'ID',
      dataIndex: 'id',
      hideInSearch: true,
      width: '10%'
    },
    {
      title: '分类名称',
      key: 'name',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '标识',
      key: 'flag',
      dataIndex: 'flag',
      hideInSearch: true,
    },
    {
      title: '父级ID',
      dataIndex: 'pid',
      hideInSearch: true,
      hideInTable: true
    },
    {
      key: 'status',
      title: '状态',
      dataIndex: 'status',
      filters: true,
      onFilter: true,
      render: (_, record) => {
        return (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
            defaultChecked={record.status === 1}
            onChange={() => handleChangeStatus(record)}
          />
        )
      }
    },
    {
      title: '分组',
      dataIndex: 'category_group_id',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '操作',
      render: (text, record) => [
        <Button
          key="action"
          type="primary"
          size="small"
          onClick={() => {
            setCategoryDetail(text)
            setUpdateModalVisit(true)
          }}
        >
          编辑
        </Button>
      ]
    },
  ]

  return (
    <PageContainer header={{
      extra: [
        <GetTime key="getTime"/>
      ]
    }}>
      <ProTable
        actionRef={actionRef}
        columns={columns}
        params={{ category_group: props.route.category_group }}
        request={async params => {
          setLoading(true)
          const data = await categoryList(params)
          setCategoryLists(data)
          setLoading(false)
          return {
            data: data,
            success: true,
          }
        }}
        loading={loading}
        rowKey="id"
        pagination={false}
        headerTitle="分类表格"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined/>} onClick={() => setCreateModalVisit(true)} type="primary">
            新建
          </Button>,
        ]}
      />
      <CreateForm
        createCategory={handleCreateCategory}
        createModalVisit={createModalVisit}
        setCreateModalVisit={() => setCreateModalVisit(false)}
        group={group}
        initialValue={props.route.category_group}
        treeData={treeData}
        categoryLists={categoryLists}
      />
      <UpdateForm
        updateModalVisit={updateModalVisit}
        setUpdateModalVisit={() => setUpdateModalVisit(false)}
        updateCategory={updateCategory}
        group={group}
        treeData={treeData}
        categoryDetail={categoryDetail}
        initialValue={props.route.category_group}
        categoryLists={categoryLists}
      />
    </PageContainer>
  )
}

export default Index
